package MapAndSet;

public class BinarySearchTree {
    static  class TreeNode{
        public int val;
        public  TreeNode left;
        public  TreeNode right;
        public TreeNode(int val){
            this.val =val;
        }
    }
    public  TreeNode root;
    public void insert(int key){
        if (root==null){
            root = new TreeNode(key);
            return;
        }
        TreeNode cur = root;
        TreeNode parent = null;
        TreeNode node = new TreeNode(key);
        while (cur !=null){
            if (cur.val<key){
                parent = cur;
                cur = cur.right;
            }else if(cur.val>key){
                parent = cur;
                cur = cur.left;
            }else {
                //不能同时插入2个相同的数据
                return;
            }
        }
        if(parent.val>key){
            parent.left = node;
        }else {
            parent.right = node;
        }

    }

    /**
     * 时间复杂度： 最好情况：O(logN)
     *            最坏情况：O(N)
     * @param key
     * @return
     */
    public TreeNode search(int key){
        TreeNode cur = root;
        while (cur !=null){
            if (cur.val<key){
                cur = cur.right;
            } else if (cur.val==key) {
                return cur;
            }else{
                cur =cur.left;
            }
        }
        return  null;
    }
    public  void remove(int key){
        TreeNode cur =root;
        TreeNode parent = null;
        while (cur !=null){
            if (cur.val<key){
                parent =cur;
                cur= cur.right;
            } else if (cur.val>key) {
                parent =cur;
                cur =cur.left;
            }else{
                removeNode(parent,cur);
                return;
            }
        }
    }
    private  void removeNode(TreeNode parent,TreeNode cur){
        if(cur.left==null){
            if (root==null){
                root = cur.right;
            } else if (cur.left==null) {
                parent.left = cur.right;
            }else{
                parent.right = cur.right;
            }
        } else if (cur.right==null) {
            if (root==null){
                root = cur.left;
            } else if (cur.left==null) {
                parent.left = cur.left;
            }else{
                parent.right = cur.left;
            }
        }else {
            TreeNode TargetParent = cur;
            TreeNode Target = cur.right;
            while (Target.left !=null){
                TargetParent = Target;
                Target = Target.left;
            }
            cur.val = Target.val;
            if (TargetParent.left==Target){
                TargetParent.left = Target.right;
            }else {
                TargetParent.right = Target.right;
            }
        }
    }
}
